package cn.chenhao.org.service.impl;

import cn.chenhao.basic.service.impl.BasicServiceImpl;
import cn.chenhao.basic.util.MD5Utils;
import cn.chenhao.basic.util.StrUtils;
import cn.chenhao.org.domain.Employee;
import cn.chenhao.org.mapper.EmployeeMapper;
import cn.chenhao.org.service.IEmployeeService;
import cn.chenhao.user.domain.Logininfo;
import cn.chenhao.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmployeeServiceImpl extends BasicServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper loginInfoMapper;

    @Override
    public void add(Employee employee) {
        initEmployee(employee);
        Logininfo loginInfo = employee2LoginInfo(employee);
        loginInfoMapper.save(loginInfo);
        employee.setLogininfo_id(loginInfo.getId());
        employeeMapper.save(employee);
    }

    private Logininfo employee2LoginInfo(Employee employee) {
        Logininfo loginInfo = new Logininfo();
        BeanUtils.copyProperties(employee, loginInfo);
        loginInfo.setType(0);// 0是后台管理人员
        return loginInfo;
    }

    private void initEmployee(Employee employee) {
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 使用盐值加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }


    @Override
    public void update(Employee employee) {
        initEmployee(employee);
        Logininfo loginInfo = employee2LoginInfo(employee);
        loginInfoMapper.update(loginInfo);
        employee.setLogininfo_id(loginInfo.getId());
        employeeMapper.update(employee);
    }

    @Override
    public void delete(Long eid) {
        Employee employee = employeeMapper.loadById(eid);
        loginInfoMapper.remove(employee.getLogininfo_id());
        employeeMapper.remove(eid);
    }
}
